package com.wejoy.video.middle.station.admin.controller.alarm;

import com.alibaba.fastjson2.JSONObject;
import com.wejoy.video.middle.station.admin.controller.BaseController;
import com.wejoy.video.middle.station.admin.util.CurrentUserUtils;
import com.wejoy.video.middle.station.data.domain.PageResult;
import com.wejoy.video.middle.station.data.domain.alarm.AlarmDetails;
import com.wejoy.video.middle.station.data.domain.system.SysUser;
import com.wejoy.video.middle.station.data.enums.dict.EnumWorkAlarmType;
import com.wejoy.video.middle.station.data.service.alarm.IAlarmDetailsService;
import com.wejoy.video.middle.station.data.service.evs.IEvsHttpService;
import com.wejoy.video.middle.station.data.util.WJAssert;
import com.wejoy.video.middle.station.data.vo.AlarmDataVO;
import com.wejoy.video.middle.station.data.vo.RespJSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.time.LocalTime;
import java.util.*;

/**
 * 工单主表
 *
 * @author miracle_j
 * @date 2024年12月12日 15:18:52
 */
@RestController
@RequestMapping("/alarm/alarmDetails")
public class AlarmDetailsController extends BaseController {

    @Autowired
    private IAlarmDetailsService alarmDetailsService;
    @Autowired
    private IEvsHttpService evsHttpService;



    /**
     * 分页查询
     *
     * @param alarmDetailsReq alarmDetailsReq
     * @return RespJSON
     */
    @PostMapping("/getPageList")
    public RespJSON getPageList(@RequestBody AlarmDetails alarmDetailsReq) {
        if(alarmDetailsReq.getEndTime()!=null){
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(alarmDetailsReq.getEndTime());
            calendar.set(Calendar.HOUR_OF_DAY, 23);
            calendar.set(Calendar.MINUTE, 59);
            calendar.set(Calendar.SECOND, 59);
            calendar.set(Calendar.MILLISECOND, 999);
            alarmDetailsReq.setEndTime(calendar.getTime());
        }
        if(alarmDetailsReq.getStartTime()!=null){
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(alarmDetailsReq.getStartTime());
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);
            alarmDetailsReq.setStartTime(calendar.getTime());
        }
        int count = alarmDetailsService.getCount(alarmDetailsReq);
        List<AlarmDetails> list = new ArrayList<>();
        if (count > 0) {
            list = alarmDetailsService.getPageList(alarmDetailsReq);
        }
        PageResult result = new PageResult(alarmDetailsReq.getPageNo(), alarmDetailsReq.getPageSize(), count, list);
        return RespJSON.success(result);
    }



    /**
     * 主键查询
     *
     * @param id id
     * @return RespJSON
     */
    @GetMapping("/getOneById")
    public RespJSON getOneById(Long id) {
//        evsHttpService.getDepartmentsJson();
        AlarmDetails oneById = alarmDetailsService.getOneById(id);
        Date triggerTime = oneById.getTriggerTime();
        // 获取毫秒时间戳
        long triggerTimeMillis = triggerTime.getTime();
        // 计算前十秒和后十秒的毫秒时间戳
        long beforeTenSecondsMillis = triggerTimeMillis - 10 * 1000;
        long afterTenSecondsMillis = triggerTimeMillis + 10 * 1000;
        // 转换为秒级时间戳（如果需要）
        long beforeTenSeconds = beforeTenSecondsMillis / 1000;
        long afterTenSeconds = afterTenSecondsMillis / 1000;
        JSONObject result = new JSONObject();
        long l = System.currentTimeMillis();
        JSONObject afterCloudRecordList = evsHttpService.getCloudRecordList(evsHttpService.getToken(), oneById.getDeviceId().intValue(), 1, 1, beforeTenSeconds + "", triggerTimeMillis / 1000 + "");
        JSONObject beforeCloudRecordList = evsHttpService.getCloudRecordList(evsHttpService.getToken(), oneById.getDeviceId().intValue(), 1, 1, triggerTimeMillis / 1000 + "", afterTenSeconds + "");
//        JSONObject afterLocalRecordList = evsHttpService.getLocalRecordList(evsHttpService.getToken(), oneById.getDeviceId().intValue(), beforeTenSeconds + "", triggerTimeMillis / 1000 + "");
//        JSONObject beforeLocalRecordList = evsHttpService.getLocalRecordList(evsHttpService.getToken(), oneById.getDeviceId().intValue(),triggerTimeMillis / 1000 + "", afterTenSeconds + "");
        long l2 = System.currentTimeMillis();
        System.out.println(l2-l);
        result.put("beforeVideo",afterCloudRecordList.get("data"));
        result.put("afterVideo",beforeCloudRecordList.get("data"));
//        result.put("beforeLocalVideo",afterLocalRecordList.get("data"));
//        result.put("afterLocalVideo",beforeLocalRecordList.get("data"));
        return RespJSON.success(result);
    }
    @GetMapping("" +
            "/getCountByalarmLocation")
    public RespJSON getCountByalarmLocation(Long deptId){
        AlarmDetails alarmDetails = new AlarmDetails();
        alarmDetails.setDeptId(deptId);
        List<Map<String, String>> countByalarmLocation = alarmDetailsService.getCountByalarmLocation(alarmDetails);
        for (EnumWorkAlarmType alarmType : EnumWorkAlarmType.values()) {
            if (countByalarmLocation.stream().noneMatch(map -> map.get("alarmLocation").equals(alarmType.getText()))) {
                Map<String, String> map = new HashMap<>();
                map.put("alarmLocation", alarmType.getText());
                map.put("count", "0");
                countByalarmLocation.add(map);
            }
        }
        return RespJSON.success(countByalarmLocation);
    }

    @PostMapping("/getAlarmDataByDate")
    public RespJSON getAlarmDataByDate(@RequestBody AlarmDetails alarmDetails) {
        Date startTime = alarmDetails.getStartTime();
        Date endTime = alarmDetails.getEndTime();
        // 如果 startTime 和 endTime 为空，默认设置为查询最近 7 天
        if (endTime == null) {
            endTime = new Date();
        }
        if (startTime == null) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(endTime);
            calendar.add(Calendar.DAY_OF_YEAR, -6);
            startTime = calendar.getTime();
        }
        // 生成 startTime 到 endTime 这段日期的 yyyy-MM-dd 格式的 List<String> 集合
        List<String> dateList = generateDateList(startTime, endTime);
        List<Integer> countList = new ArrayList<>();
        AlarmDetails queryDetails = new AlarmDetails();
        queryDetails.setDeptId(alarmDetails.getDeptId());
        dateList.forEach(date -> {
            try {
                // 获取当前日期的 0 点 0 分 0 秒
                Date dateStart = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(date + " 00:00:00");
                // 获取当前日期的 23 点 59 分 59 秒
                Date dateEnd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(date + " 23:59:59");
                // 创建新的 AlarmDetails 实例，设置日期范围
                queryDetails.setStartTime(dateStart);
                queryDetails.setEndTime(dateEnd);
                // 调用服务获取计数
                int count = alarmDetailsService.getCount(queryDetails);
                countList.add(count);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        // 使用现有的 AlarmDataVO 实体封装结果
        AlarmDataVO alarmDataVO = new AlarmDataVO();
        alarmDataVO.setDateList(dateList);
        alarmDataVO.setTotal(countList);
        return RespJSON.success(alarmDataVO);
    }

    /**
     * 生成两个日期之间的日期列表，格式为 yyyy-MM-dd
     *
     * @param start 开始日期
     * @param end   结束日期
     * @return 日期列表
     */
    private List<String> generateDateList(Date start, Date end) {
        List<String> dateList = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        Date currentDate = start;
        while (!currentDate.after(end)) {
            dateList.add(sdf.format(currentDate));
            // 增加一天
            currentDate = new Date(currentDate.getTime() + 24 * 60 * 60 * 1000);
        }

        return dateList;
    }

}
